package su.security.service.impl;

import java.sql.SQLException;
import java.util.List;

import net.kuakao.core.dto.PagerDTO;
import net.kuakao.core.exception.DataBaseException;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import su.base.Constants;
import su.security.dao.ISecurityModuleDAO;
import su.security.dao.ISecurityUrlDAO;
import su.security.dao.ISecurityUserDAO;
import su.security.entity.SecurityModule;
import su.security.entity.SecurityUrl;
import su.security.entity.SecurityUser;
import su.security.service.SecurityUserService;
import su.tool.Configuration;
import su.tool.Md5;

public class SecurityUserServiceImpl implements SecurityUserService {
	@Autowired
	private ISecurityUserDAO userDAO;
	@Autowired
	private ISecurityUrlDAO urlDAO;
	@Autowired
	private ISecurityModuleDAO moduleDAO;
	protected final Log log = LogFactory.getLog(getClass());
	//==============
	public List<SecurityUser> queryByPage(PagerDTO s){
		List<SecurityUser> res = null;
		try {
			res = userDAO.queryByPage(s);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		if(res==null || res.isEmpty())return null;
		for(SecurityUser u : res){
			u.setModulesStr(this.getStrByModuleids(u.getModuleids()));
		}
		return res;
	}
	public SecurityUser getBaseinfo(int id){
		SecurityUser baseinfo = null;
		try {
			baseinfo = userDAO.getBaseinfo(id);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		return baseinfo;
	}
	public SecurityUser login(String username,String userpwd){
		SecurityUser baseinfo = null;
		try {
			baseinfo = userDAO.login(username, userpwd);	
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return baseinfo;
	}
	
	public boolean urlCanDo(int userId,String url){
		List<SecurityUrl> urls = null;
		try {
			urls = urlDAO.getListByUrl(url);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		if(urls==null || urls.isEmpty()){//url未受控
			String sl = Configuration.getInstance().getValue("security.level");
			if("1".equals(sl))return true;
			else return false;
		}else{
			if(urls.size()>1)log.error("---------su error,the size of url is >1,url:"+url);
			SecurityUrl su = urls.get(0);
			//取用户可以访问的所有url
			SecurityUser user = null;
			try {
				user = userDAO.getBaseinfo(userId);
			} catch (SQLException e) {
				log.error(e.getMessage());
			}
			if(user==null)return false;
			List<SecurityModule> modules = null;
			try {
				modules = moduleDAO.getModuleList(user.getModuleids());
			} catch (SQLException e) {
				log.error(e.getMessage());
			}
			if(modules==null || modules.isEmpty())return false;
			for(SecurityModule m : modules){
				String urlids = m.getUrlids();
				if(StringUtils.isBlank(urlids))continue;
				String[] idStrs = urlids.split(",");
				for(String idStr : idStrs){
					if(String.valueOf(su.getId()).equals(idStr))return true;
				}
			}
			return false;
		}
		
	}
	/**
	 * 根据module的id字符串取得其对应的名称的字符串
	 */
	private String getStrByModuleids(String moduleids){
		if(StringUtils.isBlank(moduleids))return "";
		List<SecurityModule> list = null;
		try {
			list = moduleDAO.getModuleList(moduleids);
		} catch (SQLException e) {
			log.error(e.getMessage());
		}
		if(list==null || list.isEmpty())return "";
		String res = "";
		for(SecurityModule m : list){
			if(!"".equals(res))res+=",";
			res += m.getModulename();
		}
		return res;
	}
	//---------------
	public void save(SecurityUser o)throws Exception {
		o.setStatus(Constants.STATUS_ENABLE);
		if(o.getId()==0){
			o.setUsertype(1);//默认值，普通管理员
			o.setUserpwd(Md5.md5("123"));//md5加密,默认密码123
			userDAO.insert(o);
		}else{
			userDAO.update(o);
		}
	}
	public void remove(int id)throws Exception{
		userDAO.remove(id);
	}
	public void updatePwd(String username,String userpwd,String newpwd)throws Exception{
		SecurityUser user = this.login(username, userpwd);
		if(user==null){
			throw new DataBaseException("用户名或密码错误，请重新输入或找管理员重置");
		}
		this.operateResetPwd(newpwd, user.getId());
	}
	public void operateResetPwd(String userpwd,int userId)throws Exception{
		userDAO.operateResetPwd(Md5.md5(userpwd), userId);
	}
}
